#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <unordered_map>
#include <fstream>
#include <stdio.h>
#include <signal.h>
using namespace std;
using namespace Server;

const string dictTxt = "./dict.txt";
unordered_map<string, string> dict;

static void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << "local_port\n"
         << endl;
}

static bool cutString(const string &target, string *s1, string *s2, const string &sep)
{
    auto pos = target.find(sep);
    if (pos == string::npos)
        return 0;
    *s1 = target.substr(0, pos);
    *s2 = target.substr(pos + sep.size());
    return 1;
}

static void initDict()
{
    ifstream in(dictTxt, ios::binary);
    if (!in.is_open())
    {
        cerr << "open file " << dictTxt << " error" << endl;
        exit(OPEN_ERR);
    }

    string line;
    string key, value;
    while (getline(in, line))
    {
        // cout << line << endl;
        if (cutString(line, &key, &value, ":"))
        {
            dict.insert(make_pair(key, value));
        }
    }

    in.close();

    cout << "load dict success" << endl;
}

void reload(int signo)
{
    (void)signo;
    initDict();
}
static void dubugPrint()
{
    for (auto &it : dict)
    {
        cout << it.first << "  #   " << it.second << endl;
    }
}

// demo1
void handleMessage(int sockfd, string clientip, uint16_t clientport, string message)
{
    // 对message进行特定的业务处理  不关心message是怎么来的----> server通信和业务逻辑解耦
    cout << clientip << "[" << clientport << "] # " << message << endl;
    string response_message;

    dubugPrint();
    auto iter = dict.find(message);
    if (iter == dict.end())
        response_message = "unkown";
    else
        response_message = iter->second;

    // 开始返回
    struct sockaddr_in client;
    bzero(&client, sizeof(client));
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr(clientip.c_str());
    client.sin_port = htons(clientport);

    sendto(sockfd, response_message.c_str(), response_message.size(), 0, (struct sockaddr *)&client, sizeof(client));

    // cout << who << "[" << clientport << "]#" << message << endl;
    // return;
}

// demo2
void execCommand(int sockfd, string clientip, uint16_t clientport, string cmd)
{
    // cmd解析   ls -a -l
    string response;
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
        response = cmd + "exec failed";
    char line[1024];
    while (fgets(line, sizeof(line), fp))
    {
        response += line;
    }
    pclose(fp);

    // 开始返回
    struct sockaddr_in client;
    bzero(&client, sizeof(client));
    client.sin_family = AF_INET;
    client.sin_addr.s_addr = inet_addr(clientip.c_str());
    client.sin_port = htons(clientport);

    sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&client, sizeof(client));
}

//demo3
void routeMessage(int sockfd, string clientip, uint16_t clientport, string cmd)
{

}

// ./udpServer port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    // string ip = argv[1];
    // signal(2, reload);
    // initDict();
    // dubugPrint();
    // std::unique_ptr<udpServer> usvr(new udpServer(handleMessage, port));

    //std::unique_ptr<udpServer> usvr(new udpServer(execCommand, port));

    std::unique_ptr<udpServer> usvr(new udpServer(routeMessage, port));
    usvr->initServer();
    usvr->start();
    return 0;
}